import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_uikit/t2mini/animation/FlipCardComponent.dart';
import 'package:flutter_uikit/t2mini/bean/CardBean.dart';
import 'package:flutter_uikit/t2mini/bean/PayBean.dart';
import 'package:flutter_uikit/t2mini/view/AlertUtil.dart';
import 'package:flutter_uikit/t2mini/view/IconText%20.dart';
import 'package:flutter_uikit/t2mini/view/RowTextView.dart';
import 'package:flutter_uikit/t2mini/view/calculator/calculatorView.dart';
import 'package:flutter_uikit/utils/FlipAnimation.dart';
import 'package:flutter_uikit/utils/NativeCall.dart';
import 'package:flutter_uikit/utils/Tools.dart';
import 'package:flutter_uikit/utils/uidata.dart';
import 'package:toast/toast.dart';

class TradePage extends StatefulWidget {
  @override
  _TradePageState createState() => _TradePageState();
}

class _TradePageState extends State<TradePage> {
  BuildContext context;
  EventChannel eventChannel;
  GlobalKey<FlipCardComponentState> globalKey = GlobalKey(); //设置key,绑定待刷新控件.
  var needPay = "0.00"; //显示支付金额
  var _payState = "本单应收"; // 提示信息
  PayBean _payResult;
  Color _lockColor = Colors.white;
  Timer _countdownTimer;
  int _countdownNum = 3;
  bool startPay = false;
  void _onEvent(Object event) {
    if (mounted) {
      //mounted 是 bool 类型，表示当前 State 是否加载到树⾥。常用于判断页面是否释放。
      setState(() {
        _payState = "正在支付";
      });

      Future<CardBean> cardBean = NativeCall.getInstance().cardGet({
        "type": "20",
        "shop": "107",
        "term": "142",
        "ver": "20201223",
        "cid": event,
        "account": "-1",
        "key": "b24034b1b84442cea0ae1f2822b952ae"
      });
      cardBean.then((value) {
        if (value.code == 1) {
          startPayTask(event);
        } else {
          Toast.show(value.msgCn, context,
              duration: Toast.LENGTH_LONG, gravity: Toast.CENTER);
        }
      });
    }
  }

  void startPayTask(String cid) {
    String invoiceNum = "142" + Tools.currentTimeMillis().toString();
    String date = Tools.getTime(Tools.FORMATTER1);
    NativeCall.getInstance().dishPay({
      "t": "2111",
      "shop": "107",
      "key": "b24034b1b84442cea0ae1f2822b952ae",
      "term": "142",
      "part": "1",
      "cid": cid,
      "prods": "0,0," + needPay + "元菜," + needPay + ",0,0,0,0,,null,null",
      "amt": needPay,
      "cno": cid,
      "pays": "1," + needPay + ",0.00," + cid + "," + cid,
      "policy": "1",
      "pay_date": date,
      "invoice": invoiceNum,
      "auto_account": "1",
      "gage": "0",
    }).then((pay) {
      setState(() {
        if (pay.code == 1) {
          _payResult = pay;
          _payResult.card = cid;
          _payState = "支付成功!";
          reGetCountdown();
        } else {
          _payState = "支付失败!";
          Toast.show(pay.msgCn, context,
              duration: Toast.LENGTH_LONG, gravity: Toast.CENTER);
        }
      });
    });
  }

  void _onError(Object error) {
    if (mounted) {
      setState(() {
        print(error);
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    globalKey = null;
    eventChannel = null;
  }

  @override
  void initState() {
    super.initState();
    eventChannel = const EventChannel('nfc');
    eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  }

  @override
  Widget build(BuildContext context) {
    this.context = context;
    return Scaffold(
      backgroundColor: Color.fromRGBO(235, 236, 238, 1),
      body: Stack(overflow: Overflow.visible, children: [
        topView(context),
        payInfoShow(context),
        calculaton(),
      ]),
    );
  }

  Container topView(BuildContext context) {
    return Container(
      height: 210,
      color: UIData.myAppColor,
      child: Padding(
        padding: const EdgeInsets.only(top: 18.0),
        child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                  width: 150,
                  padding: EdgeInsets.only(left: 20),
                  alignment: Alignment.topLeft,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Icon(
                      Icons.arrow_back,
                      size: 34,
                      color: Colors.white,
                    ),
                  )),
              Container(
                  alignment: Alignment.topCenter,
                  width: 150,
                  child: Text(
                    "定价收银",
                    style: TextStyle(color: Colors.white, fontSize: 28),
                  )),
              GestureDetector(
                onTap: () {
                  AlertUtil().normolAlert(
                      context, modeDE() ? "是否启用定额模式" : "是否退出定额模式", () {
                    Navigator.of(context).pop();
                  }, () {
                    setState(() {
                      if (modeDE()) {
                        _lockColor = Colors.white;
                      } else {
                        _lockColor = Colors.red;
                      }
                    });
                    Navigator.of(context).pop();
                  });
                },
                child: Container(
                    alignment: Alignment.topCenter,
                    width: 150,
                    child: Text(
                      "锁定",
                      style: TextStyle(color: _lockColor, fontSize: 28),
                    )),
              ),
            ]),
      ),
    );
  }

//倒计时
  void reGetCountdown() {
    setState(() {
      if (_countdownTimer != null) {
        return;
      }
      // Timer的第一秒倒计时是有一点延迟的，为了立刻显示效果可以添加下一行。

      _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
        setState(() {
          if (_countdownNum > 0) {
            _payState = '支付成功(${_countdownNum--})';
          } else {
            if (!modeDE()) {
              needPay = "0.00";
              startPay = false;
            }
            _payState = '本单应收';
            _payResult = null;
            _countdownNum = 3;
            _countdownTimer.cancel();
            _countdownTimer = null;
          }
        });
      });
    });
  }

  bool modeDE() {
    return _lockColor == Colors.red;
  }

//计算器部分
  Container calculaton() {
    return Container(
        width: 540,
        height: 607,
        margin: EdgeInsets.only(
          left: 780,
          top: 90,
        ),
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: Colors.white,
          ),
          padding: EdgeInsets.all(15.0),
          child: FlipCardComponent(
            key: globalKey,
            frontComponent: Container(
              height: 600,
              width: 600,
              child: Center(
                child: CalculatorView(
                  submitPrice: (v) {
                    globalKey.currentState.animate();
                  },
                ),
              ),
            ),
            backComponent: Center(
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                  SizedBox(
                      width: 140.0,
                      height: 70.0,
                      child: OutlineButton(
                        child: Text(
                          '取消支付',
                          style: TextStyle(fontSize: 25),
                        ),
                        onPressed: () {
                          globalKey.currentState.animate();
                          setState(() {
                            needPay = "0.00";
                            _payState = '本单应收';
                            startPay = false;
                          });
                        },
                      )),
                ])),
          ),
        ));
  }

  Widget calculatorView() {
    if (startPay) {
      return Center(
          child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
        SizedBox(
            width: 140.0,
            height: 70.0,
            child: OutlineButton(
              child: Text(
                '取消支付',
                style: TextStyle(fontSize: 25),
              ),
              onPressed: () {
                setState(() {
                  needPay = "0.00";
                  _payState = '本单应收';
                  startPay = false;
                });
              },
            )),
      ]));
    } else {
      return CalculatorView(
        submitPrice: (v) {
          setState(() {
            startPay = true;
            needPay = v;
          });
        },
      );
    }
  }

//显示支付信息
  Container payInfoShow(BuildContext context) {
    return Container(
      height: 730,
      width: MediaQuery.of(context).size.width - 600,
      margin: EdgeInsets.only(
        left: 20,
        top: 90,
      ),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(left: 38.0),
            height: 455,
            color: Colors.white,
            child: Column(
              children: [
                Container(
                  height: 120,
                  decoration: BoxDecoration(
                    color: Colors.white,
                  ),
                  child: Row(
                    //支付提示
                    children: [
                      Visibility(
                        visible: _payState != "本单应收",
                        child: Image.asset(
                          _payState == "支付失败!"
                              ? UIData.payFail
                              : _payState.contains("支付成功")
                                  ? UIData.paySuccess
                                  : UIData.payLoad,
                          width: 30,
                          height: 30,
                        ),
                      ),
                      SizedBox(width: 5),
                      Text(
                        _payState,
                        style: TextStyle(
                            fontSize: 23, fontWeight: FontWeight.bold),
                      )
                    ],
                  ),
                ),
                Container(
                  //支付金额数字
                  height: 90,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(bottom: 5.0),
                        child: Align(
                            alignment: Alignment.bottomLeft,
                            child: Text(
                              "￥",
                              style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 33,
                                  color: UIData.myTextColor),
                            )),
                      ),
                      Align(
                        alignment: Alignment.bottomLeft,
                        child: Text(
                          needPay,
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 83,
                              color: UIData.myTextColor),
                        ),
                      )
                    ],
                  ),
                ),
                payDatil(),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.only(left: 25, top: 15),
            color: Colors.white,
            height: 135,
            margin: EdgeInsets.only(top: 15),
            child: Stack(children: [
              Text("最近一单",
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 21,
                      color: UIData.myTextColor)),
              Container(
                margin: EdgeInsets.only(top: 52),
                child: Row(
                  children: [
                    IconText(
                      "123412435346346",
                      icon: Icon(Icons.insert_drive_file),
                      style: TextStyle(
                          color: UIData.myTextColor,
                          fontWeight: FontWeight.bold,
                          fontSize: 18),
                    ),
                    SizedBox(width: 43),
                    IconText(
                      "12.00",
                      icon: Icon(Icons.payment),
                      style: TextStyle(
                          color: UIData.myTextColor,
                          fontWeight: FontWeight.bold,
                          fontSize: 18),
                    ),
                  ],
                ),
              ),
            ]),
          ),
        ],
      ),
    );
  }

//账户余额等信息
  Container payDatil() {
    if (_payResult == null) {
      return Container(
        margin: EdgeInsets.only(top: 55),
        alignment: Alignment.centerLeft,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            new Container(
              margin: EdgeInsets.only(top: 15),
              color: Color.fromRGBO(235, 236, 238, 1),
              height: 40.0,
              width: 380,
            ),
            new Container(
              margin: EdgeInsets.only(top: 15),
              color: Color.fromRGBO(235, 236, 238, 1),
              height: 40.0,
              width: 350,
            ),
            new Container(
              margin: EdgeInsets.only(top: 15),
              color: Color.fromRGBO(235, 236, 238, 1),
              height: 40.0,
              width: 260,
            ),
          ],
        ),
      );
    } else {
      return Container(
        margin: EdgeInsets.only(top: 55),
        child: Stack(children: [
          Text("支付信息",
              style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 21,
                  color: UIData.myTextColor)),
          Container(
            margin: EdgeInsets.only(top: 32),
            child: Row(
              children: [
                Column(
                  children: [
                    RowTextView(
                      leftText: "支付方式",
                      centerText: "卡支付",
                    ),
                    RowTextView(
                      leftText: "支付金额",
                      centerText: _payResult.amt,
                    ),
                    RowTextView(
                      leftText: "优惠金额",
                      centerText: _payResult.rebate,
                    ),
                  ],
                ),
                SizedBox(width: 40),
                Column(
                  children: [
                    RowTextView(
                      leftText: "主  账  户",
                      centerText: _payResult.payment[0].account == 0
                          ? _payResult.payment[0].amt
                          : "0.00",
                      rightText: _payResult.payment2[0].bal,
                      showRight: true,
                    ),
                    RowTextView(
                      leftText: "补贴账户",
                      centerText: _payResult.payment[0].account == 1
                          ? _payResult.payment[0].amt
                          : "0.00",
                      rightText: _payResult.payment2[1].bal,
                      showRight: true,
                    ),
                    RowTextView(
                      leftText: "卡        号",
                      centerText: _payResult.card,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ]),
      );
    }
  }
}
